<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\Business;
use App\Model\Device;
use App\Model\DistributorDevice;
use App\Model\Order;
use App\Model\YDevice;
use App\Model\YDistributorDevice;
use App\Model\YDistributors;
use App\Model\YStation;
use App\Services\SmsService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;
use App\Services\AdapayService;

class YDistributorsController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Admin $admin;
    #[Inject]
    protected Distributors $distributors;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**经销商列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */

    public function getList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs([
            'page',
            'limit',
            'keyword',
            'is_active'
        ]);
        $page['info'] = $this->admin->getInfo($request);
        $query = YDistributors::where(function ($query) use ($page) {
            if (!empty($page['keyword'])) {
                $query->where('name', 'like', "%{$page['keyword']}%")
                    ->orWhere('phone', 'like', "%{$page['keyword']}%");
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
        });
        $data['total'] = $query->count();
        $data['list'] = $query->withCount([
            'deviceProfit as distributor_profit' => function($q) {
                $q->select(Db::raw('SUM(profit)'));
            },
            'device as device_count',
        ])
            ->orderBy('device_count', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
            ->get(['id','name','phone','owner_name'])
            ->map(function ($item) {
                // 确保统计字段存在（Hyperf特殊处理）
                return array_merge($item->toArray(), [
                    'device_count' => $item->device_count ?? 0,
                    'distributor_profit' => $item->distributor_profit ?? 0
                ]);
            });
        return $this->success($data);
    }


    public function getStationList(RequestInterface $request){
        $page = $request->inputs([
            'page',
            'limit',
            'distributor_id',
        ]);
        $query = YStation::query();
        $query->where('distributor_id',$page['distributor_id']);
        $data['list'] = $query->get();
        $data['total'] = $query->count();
        return $this->success($data);
    }

    public function getDeviceList(RequestInterface $request){
        $page = $request->inputs([
            'page',
            'limit',
            'distributor_id',
        ]);
        $query = YDevice::query();
        $query->where('distributor_id',$page['distributor_id']);
        $data['list'] = $query->with('profit')->get();
        $data['total'] = $query->count();
        return $this->success($data);
    }

    public function changeStatus(RequestInterface $request){
        $data = $request->inputs([
            'id',
            'is_active',
        ]);
        $model = YDistributors::where('id',$data['id'])->first();
        $model->is_active = $data['is_active'];
        $model->save();
        return $this->success();

    }

}
